import sys
import time
import logging
import struct
import threading
from smap.driver import SmapDriver
from smap.loader import SmapLoadError
from smap.util import periodicSequentialCall
import MySQLdb
import datetime, calendar
from twisted.internet import threads, reactor

class cartV1LiveDriver(SmapDriver):
    def setup(self, opts):
        #create all the data streams (m1c1, m1c2, m2c1, m2c2, etc)
        self.moteids = {}
        self.cartids = {}
        self.calibrations = {}
        for motename in xrange(1, 90):
            t1 = self.add_timeseries('/m%i' % motename, opts.get('units_m%ic1' % motename, 'dF'), data_type="double")
            self.moteids[motename] = t1['uuid']
            calFactor1 = float(opts.get("calFactor_m%ic1" % motename, '.852674'))
            calConstant1 = float(opts.get("calConstant_m%ic1" % motename, '9.817803'))
            self.calibrations[motename] = (calFactor1, calConstant1)
        for cartname in xrange(0, 17):
            t2 = self.add_timeseries('/cart/c%i' % cartname, opts.get('units_cart%i' % cartname, 'dF'), data_type="double")
            self.cartids[cartname] = (t2['uuid'])
        
        self.period = opts.get("Period", 90)
            
    def read(self):
        self.con = MySQLdb.connect (host = '192.168.1.100', port = 3306, user = 'smap', passwd = 'G3ccFoUw', db = 'cart')
        self.cursor = self.con.cursor()        
        self.cursor.execute ("SELECT * FROM value order by time desc limit 100;")
        data = self.cursor.fetchall()
        for row in data:
            value = float(row[3])
            datatime = str(row[2])
            datatime = calendar.timegm(time.strptime(datatime,'%Y-%m-%d %H:%M:%S'))+3600*8 #8 assume PST non-DST
            sensorId = str(row[1])
            if len(sensorId) > 3:
                if len(sensorId)== 11:
                    motename = int(sensorId[0])
                else:
                    motename = int(sensorId[0:2])
                self.add(self.moteids[motename], datatime, value*self.calibrations[motename][0]+self.calibrations[motename][1])
            else:
                cartname = int(sensorId)
                self.add(self.cartids[cartname], datatime, value)
            
        self.cursor.close()

    def start(self):
        periodicSequentialCall(self.read).start(self.period)
